package cn.exrick.xboot.shop.controller;

import cn.exrick.xboot.core.common.utils.ResultUtil;
import cn.exrick.xboot.core.common.utils.SecurityUtil;
import cn.exrick.xboot.core.common.vo.Result;
import cn.exrick.xboot.core.entity.Member;
import cn.exrick.xboot.shop.entity.ShopComment;
import cn.exrick.xboot.shop.service.IShopCommentService;
import cn.exrick.xboot.shop.utils.ArticleUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
* <p>
    * 评论表  前端控制器
    * </p>
*
* @author yuhaifei
* @since 2022-01-10
*/
@RestController
@RequestMapping("/xboot/shopcomment")
public class ShopCommentController {

    @Autowired
    private IShopCommentService shopCommentService;

    @Autowired
    private SecurityUtil securityUtil;


    @GetMapping("getComment")
    public Result getComment(String tid){
        List<ShopComment> list = shopCommentService.selectCommnet(tid);
        ArticleUtils.commentNum(list);
        return ResultUtil.data(list);
    }


    void setNum(List<ShopComment> comments){
        for(ShopComment comment: comments){
            if(!comment.getChildren().isEmpty() && comment.getChildren().size() > 0){
                comment.setReplayNum(comment.getChildren().size());
                this.setNum(comment.getChildren());
            }else{
                comment.setReplayNum(0);
            }
        }
    }

    @PostMapping("setComment")
    public Result setComment(ShopComment comment){
        Member m = securityUtil.getCurrMember();
        comment.setUserId(m.getId());
        comment.setAvatar(m.getAvatar());
        comment.setNickname(m.getNickname());
        comment.setDtime(new Date());
        shopCommentService.save(comment);
        return ResultUtil.data("发布成功");
    }

    /**
     * 删除评论
     * @param id
     * @return
     */
    @PostMapping("deleteComment")
    public Result deleteComment(String id){
        shopCommentService.removeById(id);
        shopCommentService.remove(new QueryWrapper<ShopComment>().eq("parent_id", id));
        return ResultUtil.data("删除成功");
    }

}
